package secondriver.process.core;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Objects;
import net.coobird.thumbnailator.tasks.io.FileImageSink;
import net.coobird.thumbnailator.tasks.io.FileImageSource;
import net.coobird.thumbnailator.tasks.io.OutputStreamImageSink;
import net.coobird.thumbnailator.tasks.io.URLImageSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Author : secondriver
 * Date :  2016/1/7
 */
public final class ImageProcessUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImageProcessUtil.class);

    private ImageProcessUtil() {
    }

    public static BufferedImage fetch(File file) {
        Objects.requireNonNull(file, "File can't be  null.");
        if (file.exists() && file.isFile() && file.canRead()) {
            FileImageSource s = new FileImageSource(file);
            try {
                return s.read();
            } catch (IOException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
        return null;
    }

    public static BufferedImage fetch(URL url) {
        Objects.requireNonNull(url, "Url must be not null.");
        try {
            URLImageSource s = new URLImageSource(url);
            return s.read();
        } catch (IOException e) {
            LOGGER.warn(e.getMessage(), e);
        }
        return null;
    }

    public static void push(BufferedImage bufferedImage, String formatName, File file) {
        if (Objects.nonNull(bufferedImage) && Objects.nonNull(formatName) && Objects.nonNull(file)) {
            FileImageSink sink = new FileImageSink(file, true);
            try {
                sink.setOutputFormatName(formatName);
                sink.write(bufferedImage);
            } catch (IOException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
    }

    public static void push(BufferedImage bufferedImage, String formatName, OutputStream outputStream) {
        if (Objects.nonNull(bufferedImage) && Objects.nonNull(formatName) && Objects.nonNull(outputStream)) {
            try {
                OutputStreamImageSink o = new OutputStreamImageSink(outputStream);
                o.write(bufferedImage);
            } catch (IOException e) {
                LOGGER.warn(e.getMessage(), e);
            }
        }
    }
}